﻿$.extend($.fn.tree.methods, {
    search: function (jqTree, searchFun) {
        var roots = jqTree.tree("getRoots");
        return jqTree.tree("_searchChild", {
            jqTree: jqTree,
            Node: { children: roots },
            SearchFun: searchFun
        });
    },

    _searchChild: function (node, options) {
        if (options.SearchFun(options.Node)) {
            return options.Node;
        } else if (options.Node.children != null) {
            if (options.Node.children.length > 0) {
                for (var i = 0; i < options.Node.children.length; i++) {
                    if (options.SearchFun(options.Node.children[i])) {
                        return options.Node.children[i];
                    }
                }
                for (var i = 0; i < options.Node.children.length; i++) {
                    var n = options.jqTree.tree("_searchChild", {
                        jqTree: options.jqTree,
                        Node: options.Node.children[i],
                        SearchFun: options.SearchFun
                    });
                    if (n != null) {
                        return n;
                    }
                }
            }
        }

        return null;
    }
});